import React, { FC,useState,useEffect,useImperativeHandle,forwardRef } from 'react';
import { Form,Button,Input,TreeSelect,message } from 'antd';
import { getDirectoryInfoInfo,getDirectoryTreeSelect,updateDirectoryInfo } from '../../../apis/backhub/directory';

interface Directory {
  id: number;
  name: string;
  parentId:number;
  directoryPath:string;
  createDateTime?:string;
  children?:Directory[]
}
interface BaseTree {
  title: string;
  value:string;
  children?:BaseTree[]
}
const DirectoryEditForm= (props:{ directoryId,onSuccess },ref) => {
	const [treeData , setTreeData ] = useState<BaseTree[]>([]);
	const [newDirectoryName, setNewDirectoryName] = useState<string>('');
	const [directoryPath, setDirectoryPath] = useState<string>('');
	const [parentDirectoryId,setParentDirectoryId] = useState<number>(0)
	const [formEdit] = Form.useForm();
	useImperativeHandle(ref,() => ({
		  func 
		})
	);
	
	const func=()=>{
		fetchData()
		handleEdit()
	}
	useEffect(() => {
	  fetchData();
	  handleEdit()
	}, []);
	const fetchData = async() => {
		const treeRes = await getDirectoryTreeSelect({parentId:0})
		if(treeRes.status){
			setTreeData(treeRes.data.page)
		}
	};
	const handleEdit = async() => {
		const res = await getDirectoryInfoInfo(props.directoryId)
		if(res.status&&res.data.success){
			setParentDirectoryId(res.data.data.parentId)
			formEdit.setFieldsValue({
				name:res.data.data.name,
				directoryPath:res.data.data.directoryPath,
				parentId:res.data.data.parentId
			})
		}else{
			message.error(res.data.message)
		}
	};
	
	const handleEditSave=async()=>{
		const record:Directory = {
			id:props.directoryId,
			name:newDirectoryName,
			parentId:parentDirectoryId,
			directoryPath:directoryPath
		}
		const res = await updateDirectoryInfo(record)
		if(res.status&&res.data.success){
			message.success('保存成功');
		}else{
			message.error(res.data.message)
		}
	}
	return (
		<div className="upload-container">
			<Form
				form={formEdit}
				layout="vertical"
				onFinish={handleEditSave}
			>
			  <Form.Item
				label="目录名称"
				name="name"
				rules={[{ required: true, message: '请输入目录名称' }]}
			  >
				<Input 
				  value={newDirectoryName} 
				  onChange={(e) => setNewDirectoryName(e.target.value)}
				/>
			  </Form.Item>
			  <Form.Item
					label="目录路径"
					name="directoryPath"
					rules={[{ required: true, message: '请输入目录路径' }]}
				>
					<Input 
					  value={directoryPath} 
					  onChange={(e) => setDirectoryPath(e.target.value)}
					/>
			  </Form.Item>
			  <Form.Item
				  label="上级目录"
				  name="parentId"
				>
				  <TreeSelect
				    style={{ width: '100%' }}
				    value={parentDirectoryId}
				    treeData={treeData}
				    placeholder="请选择"
				    treeDefaultExpandAll
				    onChange={setParentDirectoryId}
				  />
				</Form.Item>
			  <Form.Item>
				<Button type="primary" htmlType="submit">
				  保存
				</Button>
			  </Form.Item>
			</Form>
		</div>
	);
};

export default forwardRef(DirectoryEditForm);
